<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DNA Modeling Game</title>
<script src="three.js"></script>
<script src="helvetiker.js"></script>
<script src="makeObjects.js"></script>
<script src="jquery-2.0.3.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script type="text/javascript">


    var aminoGame = true;
    var aucg = false;  //ignored if aminoGame

    var camera, scene, renderer;
    var atcg;
    var pointerDetectRay, projector, mouse2D;
    var dragged = false;
    var draggedObject;
    var overObject;

    var positions;

    var lastMouseX = -1;
    var lastMouseY = -1;

    var letters;
    var lastLetters;

    var ncubes = Math.floor(Math.random()*4 + 3); // number of cubes
    var hotkostka=0;
    var completed=false;
    var cubes2 = new Array(ncubes);

    // POSITIONS
    var ATCG_POS_X = -430;
    var ATCG_POS_Y = -200;

    var PAS_POS_X = 50;
    var PAS_POS_Y = 0;

    var PAS2_POS_X = 380;
    var PAS2_POS_Y = 0;

    var CHAIN_POS_X = 550;
    var CHAIN_POS_Y = -100;

    var WELCOME_POS_X = -300;
    var WELCOME_POS_Y = 0;

    function init() {

        camera = new THREE.PerspectiveCamera(75, window.innerWidth
                / window.innerHeight, 1, 10000);
        camera.position.z = 1000;

        scene = new THREE.Scene();
        
        makeDNAPas();
        
	if(aminoGame){
	   makeAminoBar();
	   makeTriPas();
	} else {
		letters = [ 'A', 'T', 'C', 'G' ];

	   makeAtcgBar();
	   //makeDNAChain();
	   makeDNAPas2();
	}
	 
	
	
       
        
        // makeWelcomePage();
        // makeFinalMessage();

        renderer = new THREE.WebGLRenderer({
            antialiasing : true
        });

        renderer.setSize(window.innerWidth, window.innerHeight - 100);
        renderer.domElement.style.position = 'absolute';
        renderer.domElement.style.top = '100px';

        renderer.setClearColorHex(0xCCCCCC, 1.0);
        renderer.clear();

        document.body.appendChild(renderer.domElement);
        // $(renderer.domElement).css("top", "500px");
        // $(renderer.domElement).css("top", "200px");

        // renderer.domElement.add

        pointerDetectRay = new THREE.Raycaster();
        pointerDetectRay.ray.direction.set(0, -1, 0);
        projector = new THREE.Projector();
        mouse2D = new THREE.Vector3(0, 0, 0);

        // document.addEventListener("click", mouseClick);
        document.addEventListener("mousemove", mouseMove);
        document.addEventListener("mousedown", mouseDown);
        document.addEventListener("mouseup", mouseUp);

    }

    function restart(){
	

var objsToRemove = _.rest(scene.children, 1);
    _.each(objsToRemove, function( object ) {
          scene.remove(object);
    });
/*
 * scene.remove(atcg); scene.remove(dnachain); scene.remove(pas);
 * scene.remove(pas2);
 */

	// TODO restartovat stavove promenne
	completed=false;
	hotkostka=0;


        makeAtcgBar();
        makeDNAChain();
        makeDNAPas();
        makeDNAPas2();
        // makeWelcomePage();
        // makeFinalMessage();

        renderer.clear(); 


    }

function makeWelcomePage() {

        var welcome = new THREE.Object3D();

        // plane
        var cubesPlaneGeometry = new THREE.PlaneGeometry(800, 500, 1, 0);
        var cubesPlaneMaterial = new THREE.MeshBasicMaterial({
            color : Math.random()*0x0000ff,
            wireframe : false
        });

        textMaterial = new THREE.MeshBasicMaterial({
            color : 0x0000ff,
            wireframe : false
        });

        positions = new Array();

            var textGeo = new THREE.TextGeometry("Welcome", {
                size : 100,
                height : 20,
                face : "helvetiker"
            });
            textGeo.computeBoundingBox();

            var textMesh = new THREE.Mesh(textGeo, textMaterial.clone());
            textMesh.position.x = -40;
            textMesh.position.y = -40;



            // node for cube & mesh
            var node = new THREE.Object3D();
            node.add(textMesh);

            node.position.x = 10;
            node.position.y = 20;

            // positions[i] = new THREE.Vector3(node.position.x,
			// node.position.y, 0);

            welcome.add(node); // adding to welcome



        welcome.position.x =WELCOME_POS_X;
        welcome.position.y = WELCOME_POS_Y;
        welcome.position.z = 100;

        scene.add(welcome); // adding welcome to the scene
    }

    // var spheres = Array[100];

    // var dnachain;





    var animatedCubes = 0; // pocet vytvorenych kostek
    var finishedCubes = 0; // pocet padajicich

    var removeCube = null; // cube to be removed
    var removeTime = 0;

    var time;

    function animate(t){

        if(removeCube != null && removeTime <= t){
            scene.__removeObject(removeCube);
        	// scene.remove(removeCube);
            removeCube = null;
            
        }

        if( t > animatedCubes * 1000 + 500 ){
            animatedCubes++;
        }
        
        for(var i = finishedCubes +1; i<= Math.min(animatedCubes, ncubes); i++){
            pas2.children[i].position.y -= 3;
        }

        var j = Math.min(finishedCubes +1, ncubes);
        if(pas2.children[j].position.y <= j* 200 - 600){
            finishedCubes++;
        }
        

        // animation of dragged object
        if (dragged) {
            draggedObject.position.z = Math.sin(t * 0.005) * 40 +20 ;
        } else if(overObject != null){
            // overObject.children[0].material.color.setHex(0x0000aa);
            // overObject.children[1].material.color.setHex(0x0000aa);
        }

        if(movingObject != null){
            if(movingObject.position.distanceTo(desiredPosition) > 5){

            }
        }

        if(completed){
		// TEST
        	//completed = false;
	// restart();
		
        	// ANIMATION
		  cubes = pas2.children; 
		  for(var i = 0; i< ncubes; i++){
			  cubes[i+1].position.y += Math.sin(t * 0.005) * 2;
			  cubes2[i].position.y += Math.sin(t * 0.005) * 2;
			  //cubes[i+1].children[0].material.color.setHex(0x00ffff);
			  //cubes2[i].children[0].material.color.setHex(0x00ffff); 
		  }
		 



        }
        
        if(!aminoGame){
        	//dnachain.rotateY(0.01);
        }

        pointerDetectRay = projector.pickingRay(mouse2D.clone(), camera);

        timer = t * 0.003;

        requestAnimationFrame(animate);
        // textCubeNode.position.y = Math.cos(timer)*Math.cos(timer) * 10;

        // atcg.rotation.x += 0.02;
        // atcg.rotation.y += 0.03;
        // textCubeNode.rotation.y = 0.2;

        renderer.render(scene, camera);
        // window.requestAnimationFrame(animate, renderer.domElement);

    }

    

    function mouseUp(event){

        dragged = false;
        draggedObject.position.z = 0;
        // move(draggedObject, positions[0]);

        var cubes = pas2.children;

        var min = 9999999; // vzdalenost k nejblizsi
        var nearest;
        var nearestObject;

        for (var i = 1; i < ncubes+1; i++) {
            var pos = cubes[i].position.clone();
            pos.add(pas2.position);
            pos.x -= 320;
			

            var dist = draggedObject.position.distanceTo(pos);

            if (dist < min) {
                min = dist;
                nearest = pos;
                nearestObject = cubes[i];
            }
        }

        if (draggedObject.position.distanceTo(nearest) < 200 && finishedCubes >= ncubes) {

            var letterA = draggedObject.text;// getLetter(draggedObject);
            var letterB = getLetter(nearestObject);
            
            // TEST IF CORRECT ANSWER
        	var correct = false;     	
        	if(aminoGame){
        		var triplets = Tri[letterA];
            	for(var i =0; i < triplets.length; i++ ){
            		if(triplets[i] == letterB){
            			correct = true;
            		}
            	}
        	} else {
        		correct = (letterA == 'A' && letterB == 'T') || 
        			((letterA == 'T' || letterA == 'U') && letterB == 'A') ||
        			(letterA == 'C' && letterB == 'G') || 
        			(letterA == 'G' && letterB == 'C');
        	}
        	
        	// CONNECTING DRAGGED OBJECT
        	if(correct){
        		draggedObject.position = nearest;
        		if(aminoGame){
        			//draggedObject.position.x -= 110;
        			draggedObject.position.z = 0;
        		}
        		nearestObject.children[0].material.color = draggedObject.color;
        		nearestObject.children[1].material.color = draggedObject.color;

                cubes2[hotkostka] = draggedObject;
                hotkostka++;
        	} else {// WRONG ANSWER
        		//draggedObject.children[0].material.color.setHex(0xaaaaaa);
                //draggedObject.children[1].material.color.setHex(0xaaaaaa);
                
                if(removeCube != null){
                    scene.__removeObject(removeCube);
                }
                removeCube = draggedObject;
                scene.__removeObject(draggedObject);
                removeTime = time + 1000;
        	}
            
        	// HydroConnection
            if(!aminoGame && correct){
            	var n = 3;
                if(letterA == 'A' || letterA == 'T' || letterA == 'U'){
                    n = 2;
                }
                createHydroConnection(draggedObject, 0, 0, n);
            }

        } else{ // TOO FAR - PLACED ON WRONG POSITION
            // TODO
            // tady doplnte co se ma stat s pismenama, ktere uzivatel pusti
			// vpravo
            draggedObject.children[0].material.color.setHex(0xff0000);
            if(removeCube != null){
                scene.__removeObject(removeCube);
            }
            removeCube = draggedObject;
            scene.__removeObject(draggedObject);
            removeTime = time + 1000;
        }
        
        // END OF GAME
        if(hotkostka==ncubes){
            completed=true;
            // ulozeni pismen:
            if(!aminoGame){
            	for (var i = 1; i < ncubes+1; i++){
            		lastLetters[i] = translate(getLetter(cubes[i]));
            	} 
            }
        }

        draggedObject = null;


    }


    function mouseDown(event){
     event.preventDefault();
            mouse2D.x = (event.clientX / window.innerWidth) * 2 - 1;
            mouse2D.y = -(event.clientY  / window.innerHeight) * 2 + 1;
			
		

            var intersects = pointerDetectRay.intersectObjects(atcg.children, true);
            if (intersects.length > 0 && intersects[0].object != atcg.children[0]) {
                // draggedObject = intersects[0].object.parent;
                var obj = intersects[0].object.parent;
                // draggedObject = new THREE.Object3D();

                // draggedObject.add(obj.children[0].clone());
                // draggedObject.add(obj.children[1].clone());
				//var color =0x555555;
				
                draggedObject = makeCube2(obj.text, scene, obj.children[1].material.color, obj.position.x + atcg.position.x, obj.position.y + atcg.position.y);
                 
                // draggedObject.position = obj.position.clone();
                // draggedObject.position.x +=ATCG_POS_X;
                // draggedObject.position.y +=ATCG_POS_Y;


                // scene.add(draggedObject);

                lastMouseX = -1;
                lastMouseY = -1;
                dragged = true;
        }
    }




    // mouseMove
    function mouseMove(event){
        mouse2D.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse2D.y = -(event.clientY / window.innerHeight) * 2 + 1;

        var q = 200;
        if (dragged) {

            var dX = 0;
            var dY = 0;

            if (lastMouseX == -1 && lastMouseY == -1) {
                lastMouseX = mouse2D.x;
                lastMouseY = mouse2D.y;
            }

            dX = mouse2D.x - lastMouseX;
            dY = mouse2D.y - lastMouseY;

            draggedObject.position.x += dX * window.innerWidth;
            draggedObject.position.y += dY * window.innerHeight;

            lastMouseX = mouse2D.x;
            lastMouseY = mouse2D.y;
        } else {
            var intersects = pointerDetectRay.intersectObjects(
                    atcg.children, true);
            if (intersects.length > 0 && intersects[0].object != atcg.children[0]) {
                overObject = intersects[0].object.parent;
            } else {
                // overObject.children[0].material.color.setHex(0x0000ff);
                // overObject.children[1].material.color.setHex(0x0000ff);
                overObject = null;
            }
        }
    }


    function getLetter(object){
	
        return object.children[0].geometry.text;
		
		
    }

    function translate(letter){
	
	switch(letter){
		case 'A': return 'T';
		case 'T': return 'A';
		case 'C': return 'G';
		case 'G': return 'C';
	}
    }

    var movingObject;
    var desiredPosition;

    // move - moving specified object to desired position
    function move(object, target){
        movingObject = object;
        desiredPosition = target;
        object.position = target.clone();
    }
  $(function() {
        $( "input[type=submit], button" )
        .button()
        .click(function( event ) {
        event.preventDefault();
        });
    });

    $(function() {
        // $( "#dialog" ).dialog();
    });



    function webgl_detect(return_context)
{
    if (!!window.WebGLRenderingContext) {
        var canvas = document.createElement("canvas"),
             names = ["webgl", "experimental-webgl", "moz-webgl", "webkit-3d"],
           context = false;

        for(var i=0;i<4;i++) {
            try {
                context = canvas.getContext(names[i]);
                if (context && typeof context.getParameter == "function") {
                    // WebGL is enabled
                    if (return_context) {
                        // return WebGL object if the function's argument is
						// present
                        return {name:names[i], gl:context};
                    }
                    // else, return just true
                    return true;
                }
            } catch(e) {}
        }

        // WebGL is supported, but disabled
        document.write("WebGL is supported, but disabled <br/> Find out how to get it <a href='http://blog.teamtreehouse.com/the-beginners-guide-to-three-js#BrowserCompatibility' style='color:#000'>here</a>");
        return false;
    }

    // WebGL not supported
    document.write("Your browser does not seem to support <a href='http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation' style='color:#000'>WebGL</a>.<br/> Find out how to get it <a href='http://blog.teamtreehouse.com/the-beginners-guide-to-three-js#BrowserCompatibility' style='color:#000'>here</a>");
    return false;
}


  

</script>

<style>

</style>
</head>
<body>



    <script>
    if (webgl_detect()) {
        init();
        animate(new Date().getTime());
    }


    </script>

<!--<button onClick="init();">Nová hra</button>-->
</br><button onClick="location.reload(false);">Quick Restart</button>
<button onClick="location.href = 'http://www.fbmi.cvut.cz';">End Game</button>
<button onClick="location.href = 'welcome.html';">New Game</button>
<button onClick="$( '#dialog2' ).dialog();">Amins</button>
<button onclick="$('#dialog').dialog();"> Colors</button>

<div id="dialog" title="Colors" style="display:none;">
<p>
special cases - zluta
 kladne nabity -cervena 
 zaporne nabity -modra 	cervena 
 polarni - zelena 
 hydrofobni - fialova
</p>
</div>
<div id="dialog2" title="Amins" style="display:none;">
<p>Tri = new Object();
	Tri['Alanin'] = [ 'GCU', 'GCC', 'GCA', 'GCG' ];
	Tri['Valin'] = [ 'GUU', 'GUC', 'GUA', 'GUG' ];
	Tri['Kyselina asparagova'] = [ 'GAU', 'GAC', 'GAA', 'GAG' ];
	Tri['Glycin'] = [ 'GGU', 'GGC', 'GGA', 'GGG' ];
	Tri['Threonin'] = [ 'ACU', 'ACC', 'ACA', 'ACG' ];
	Tri['Asparagin'] = [ 'AAU', 'AAC' ];
	Tri['Lysin'] = [ 'AAA', 'AAG' ];
	Tri['Serin'] = [ 'AGU', 'AGC', 'UCU', 'UCC', 'UCA', 'UCG' ];
	Tri['Arginin'] = [ 'AGA', 'AGG', 'CGU', 'CGC', 'CGA', 'CGG' ];
	Tri['Histidin'] = [ 'CAU', 'CAC' ];
	Tri['Glutamin'] = [ 'CAA', 'CAG' ];
	Tri['Prolin'] = [ 'CCU', 'CCC', 'CCA', 'CCG' ];
	Tri['Leucin'] = [ 'CUU', 'CUC', 'CUA', 'CUG', 'UUA', 'UUG' ];
	Tri['Fenylalanin'] = [ 'UUU', 'UUC' ];
	Tri['Tyrosin'] = [ 'UAU', 'UAC' ];
	// UAA Ochre (Stop)3 UAG Amber (Stop)3,4 UGA Opal (Stop)3,5
	Tri['Cystein'] = [ 'UGU', 'UGC' ];
	Tri['Isoleucin'] = [ 'AUU', 'AUC', 'AUA' ];
	Tri['Methionin'] = [ 'AUG' ];
	Tri['Tryptofan'] = [ 'UGG' ];
	Tri['Threonin'] = [ 'ACU', 'ACC', 'ACA', 'ACG' ];

</p>
</div>

</body>
</html>
